package com.roadjava.rbac.controller;

import com.roadjava.rbac.bean.req.authority.AuthorityAddReq;
import com.roadjava.rbac.bean.req.authority.AuthorityUpdateReq;
import com.roadjava.rbac.bean.res.Result;
import com.roadjava.rbac.bean.vo.AuthorityTreeVO;
import com.roadjava.rbac.bean.vo.AuthorityVO;
import com.roadjava.rbac.service.AuthorityService;
import com.roadjava.rbac.security.RateLimitService;  // 引入防刷类
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.List;


@RestController
@Slf4j
@Validated
@RequestMapping("/authority")
public class AuthorityController {

    @Resource
    private AuthorityService authorityService;

    // 引入 RateLimitService
    private final RateLimitService rateLimitService = new RateLimitService();

    @GetMapping("/queryTree")
    public Result<List<AuthorityTreeVO>> queryTree() {
        return Result.buildSuccess(authorityService.queryTree());
    }

    @GetMapping("/listBackUri")
    public Result<List<String>> listBackUri() {
        return Result.buildSuccess(authorityService.listBackUri());
    }

    @PostMapping("/add")
    public Result<String> add(@RequestBody @Validated AuthorityAddReq addReq) {
        String username = addReq.getAuthorityName();
        // 假设请求体中包含用户名
        if (!rateLimitService.isAllowed(username)) {
            return Result.buildFailure("请求过于频繁，请稍后再试。");
        }

        authorityService.add(addReq);
        return Result.buildSuccess("添加成功");
    }

    @GetMapping("/queryTableTree")
    public Result<List<AuthorityVO>> queryTableTree() {
        return Result.buildSuccess(authorityService.queryTableTree());
    }

    @GetMapping("/queryById")
    public Result<AuthorityVO> queryById(@NotNull Long id) {
        return Result.buildSuccess(authorityService.queryById(id));
    }

    @PostMapping("/modifyById")
    public Result<String> modifyById(@RequestBody @Validated AuthorityUpdateReq updateReq) {
        String username = updateReq.getAuthorityName();
        // 假设请求体中包含用户名
        if (!rateLimitService.isAllowed(username)) {
            return Result.buildFailure("请求过于频繁，请稍后再试。");
        }

        authorityService.modifyById(updateReq);
        return Result.buildSuccess("修改成功");
    }

    @GetMapping("/deleteById")
    public Result<String> deleteById(@NotNull Long id) {
        // 假设通过请求中的某种方式获取用户名
        String username = id.toString(); // 实现获取用户名的逻辑
        if (!rateLimitService.isAllowed(username)) {
            return Result.buildFailure("请求过于频繁，请稍后再试。");
        }

        authorityService.deleteById(id);
        return Result.buildSuccess("删除成功");
    }



}
